package cz.none.bezbarier.web.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;

public class PNPageImpl<T> implements PNPage<T> {
	private Page<T> p;
	private List<Integer> prevPages = new ArrayList<Integer>();
	private List<Integer> nextPages = new ArrayList<Integer>();

	public PNPageImpl(Page<T> page, Integer totalPagers) {
		this.p = page;

		int currentPage = p.getNumber() + 1;
		boolean odd = totalPagers % 2 != 0;
		int lower = (odd ? (totalPagers - 1) / 2 : (totalPagers / 2) - 1);
		int upper = (odd ? (totalPagers - 1) / 2 : (totalPagers / 2));

		int counter = (currentPage - lower > 0) ? (currentPage - lower) : 1;
		while (currentPage > counter && lower > prevPages.size()) {
			prevPages.add(counter);
			counter++;
		}

		counter++;
		while (counter <= p.getTotalPages() && upper > nextPages.size()) {
			nextPages.add(counter);
			counter++;
		}

		while (counter <= p.getTotalPages() && counter <= totalPagers) {
			nextPages.add(counter);
			counter++;
		}

		counter = prevPages.size() + nextPages.size() + 1;

		while (counter < totalPagers && counter < p.getTotalPages()) {
			prevPages.add(0, prevPages.get(0) - 1);
			counter = prevPages.size() + nextPages.size() + 1;
		}
	}

	@Override
	public List<Integer> getPrevPages() {
		return prevPages;
	}

	@Override
	public List<Integer> getNextPages() {
		return nextPages;
	}

	@Override
	public int getNumber() {
		return p.getNumber();
	}

	@Override
	public int getSize() {
		return p.getSize();
	}

	@Override
	public int getTotalPages() {
		return p.getTotalPages();
	}

	@Override
	public int getNumberOfElements() {
		return p.getNumberOfElements();
	}

	@Override
	public long getTotalElements() {
		return p.getTotalElements();
	}

	@Override
	public boolean hasPreviousPage() {
		return p.hasPreviousPage();
	}

	@Override
	public boolean isFirstPage() {
		return p.isFirstPage();
	}

	@Override
	public boolean hasNextPage() {
		return p.hasNextPage();
	}

	@Override
	public boolean isLastPage() {
		return p.isLastPage();
	}

	@Override
	public Iterator<T> iterator() {
		return p.iterator();
	}

	@Override
	public List<T> getContent() {
		return p.getContent();
	}

	@Override
	public boolean hasContent() {
		return p.hasContent();
	}

	@Override
	public Sort getSort() {
		return p.getSort();
	}

}
